﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace engine
{
    class ModelNode : SceneNode
    {
        /// <summary>
        /// Scene node 3d model
        /// </summary>
        private Model model;
        private String modelName;



        /// <summary>
        /// Reference to the Game class
        /// </summary>
        /// <value></value>
        //public Game Game { get; set; }

        /// <summary>
        /// The ModelNode contructor
        /// </summary>
        public ModelNode() : this(null) { }

        public ModelNode(String modelName) : this(modelName, null, Matrix.Identity) { }

        public ModelNode(String modelName, List<SceneNode> children, Matrix transform)
            : base(children, transform)
        {
            this.modelName = modelName;
        }

        public override void LoadContent()
        {
            if (modelName != null && Scene.Content != null)
            {
                this.model = Scene.Content.Load<Model>(modelName); 
            }
        }

        public override void Draw(GameTime gameTime, Matrix parent)
        {
            DrawModel(gameTime, parent * Local);

            base.Draw(gameTime, parent);
        }

        protected virtual void DrawModel(GameTime gameTime, Matrix parent)
        {
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in model.Meshes)
            {
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = parent;
                    effect.View = scene.Camera.View;
                    effect.Projection = scene.Camera.Projection;
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }
        }

        public override void Update(GameTime gameTime)
        {
            UpdateModel(gameTime);

            base.Update(gameTime);
        }

        protected virtual void UpdateModel(GameTime gameTime) { }
    }
}
